package msgobj

import (
	"dev_gw/common"
	"encoding/json"
	"time"
)

type appHeartBeatPoint struct {
	Key  string `json:"key"`
	Val  string `json:"val"`
	Time int64  `json:"time"`
}

func newAppHeartBeatPoint(key string, val string) *appHeartBeatPoint {
	return &appHeartBeatPoint{
		Key:  key,
		Val:  val,
		Time: time.Now().UnixMilli(),
	}
}

type appHeartBeatApp struct {
	Name   string               `json:"name"`
	Status string               `json:"status"`
	Sver   string               `json:"sver"`
	Points []*appHeartBeatPoint `json:"points"`
}

func newAppHeartBeatApp(sver string, p ...*appHeartBeatPoint) *appHeartBeatApp {
	a := &appHeartBeatApp{
		Name:   common.ProcessName,
		Status: "online",
		Sver:   sver,
		Points: make([]*appHeartBeatPoint, 0),
	}

	a.Points = append(a.Points, p...)

	return a
}

func newAppHeartBeatApps(a ...*appHeartBeatApp) []*appHeartBeatApp {
	result := make([]*appHeartBeatApp, 0)
	result = append(result, a...)

	return result
}

type AppHeartBeat struct {
	Tick int                `json:"tick"`
	Time int64              `json:"time"`
	Src  string             `json:"src"`
	App  []*appHeartBeatApp `json:"app"`
}

func NewAppHeartBeat() *AppHeartBeat {
	return &AppHeartBeat{
		Tick: 1,
		Time: time.Now().UnixMilli(),
		Src:  common.ProcessName,
		App:  newAppHeartBeatApps(newAppHeartBeatApp(common.Version, newAppHeartBeatPoint("date", time.Now().Format("2006-01-02 15:04:05")))),
	}
}

func (a *AppHeartBeat) ToJson() string {
	if b, err := json.Marshal(a); err == nil {
		return string(b)
	}

	return ""
}
